package com.mt.components.utils {
	import com.mt.system.domain.OptLog;
	import com.mt.system.domain.Permission;
	import com.mt.system.domain.User;
	import com.mt.components.log.LogFactory;
	import com.mt.components.log.Logger;
	
	import mx.controls.Alert;
	import mx.core.FlexGlobals;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.mxml.RemoteObject;

	/**      
	 * 文件名称：RemoteFactory<br>
	 * 文件描述：<br>
	 * 创建人：马腾<br>
	 * 创建时间：Nov 24, 2012 12:59:41 PM<br>
	 * 修改人：马腾<br>
	 * 修改时间：Nov 24, 2012 12:59:41 PM<br>
	 */
	public class RemoteFactory {
		
		private static var logger:Logger = LogFactory.getLogger(RemoteFactory);
		
		private static var instance:RemoteFactory;
		
		public var user:User;
		
		public static function getInstance():RemoteFactory {
			if(!instance){
				instance = new RemoteFactory();
			}
			return instance;
		}
		
		public function getRemote(name:String , permissionName:String = null):RemoteObject {
			var remote:RemoteObject = new RemoteObject(name);
			remote.showBusyCursor = true;
			remote.addEventListener(FaultEvent.FAULT , fault);
			if(!StringUtils.isEmpty(permissionName)){
				remote.addEventListener(ResultEvent.RESULT , function (event:ResultEvent):void {
					writeLog(permissionName);
				});
			}
			return remote;
		}
		
		protected function writeLog(permissionName:String):void {
			var remote:RemoteObject = new RemoteObject("LogService");
			var optLog:OptLog = new OptLog();
			optLog.user = user;
			var per:Permission = new Permission();
			per.mark = permissionName;
			optLog.permission = per;
			remote.addOptLog(optLog);
			remote.addEventListener(ResultEvent.RESULT , function(event:ResultEvent):void {
				logger.debug("wirten log for " + permissionName);
			});
			remote.addEventListener(FaultEvent.FAULT , function(event:FaultEvent):void {
				logger.debug("wirten log for " + permissionName + " faliure.....");
			});
		}
		
		protected function fault(event:FaultEvent):void {
			var faultMessage:String = event.message.toString();
			if(faultMessage.indexOf("DataOperateException") == -1){
				AlertFactory.getInstance().alert(event.message.toString());
			}
			logger.debug(event.fault.rootCause.cause.cause.errorCode);
		}
	}
}